<?php
/**
 * 现金日记账
 */
class cls_agentFinance{
	protected $_validate = array();
	function __construct(){
		global $b;
		$this->db = $GLOBALS['Db'];
		$this->base = $GLOBALS['Base'];
	}

	/** 
	 * 错误代码配置
	 * @return [type] [description]
	 */
	function errDefine($code=null){
		
		$r = array(
			'1001'=>'总账表余额与总帐表收支结算结果不符',
			'1002'=>'日志账表总支出与总账表支出记录不符',
			'1003'=>'日志账表总收入与总账表充值记录不符',
			'1004'=>'日志账表支付金额超出充值',			
			'1005'=>'余额不足，无法完成支付',			
		);

			
		return $code ? $r[$code]:$r;		
	}

	/**
	 * 类型定义
	 * @return [array]     [description]
	 */
	function typeDefine(){
		
		$types = array(
			1=>array('1','代理账户充值'),	 
			3=>array('-1','代理所属用户账户续期'),	
			4=>array('1','资金手动入账'),
			5=>array('-1','资金手动出账'),
		);
		
		return $types;
	}

	/**
	 * 账户金额增加类型
	 * @return [type] [description]
	 */
	function typePlus(){
		$r = $this->typeDefine();
		$ar = array();
		foreach($r  as $k=>$v){				
			if($v[0]>0) $ar[] = $k;				
		}	
		return $ar;
	}

	/**
	 * 账户金额减少类型
	 * @return [type] [description]
	 */
	function typeReduce(){
		$r = $this->typeDefine();
		$ar = array();
		foreach($r  as $k=>$v){				
			if($v[0]<0) $ar[] = $k;				
		}	
		return $ar;
	}


	/**
	 * 添加日记帐
	 * @param  [type] $agent_id  [用户ID]
	 * @param  [type] $money [金额]
	 * @param  [type] $type  [类型，1收入，2支出，具体参考typeDefine函数定义]
	 * @return [type]        [存在err表示执行失败，否则成功]
	 * @example   [D('WechatUserMoneyLog')->insertLog(D('User')->getID(),11,1);]
	 */
	function insertLog($agent_id,$money,$type,$desc=null,$l_date=null){
		if((float)$money==0) return false;
		if(!$l_date) $l_date = date('Y-m-d H:i:s');	
		$ex = $this->db->query("select  * from {$this->base->table('agent')} where agent_id={$agent_id}",'Row');	
		//本次支付校验
		if(in_array($type,$this->typeReduce())){
			if(!$ex){
				$err =  array('err'=>array('1005'=>$this->errDefine('1005')));
				return $err;
			}else{
				//历史坏帐检查
				$err = $this->checkLog($agent_id);
				if($err) return array('err'=>$err);	
				//支付可行性检查
				$left = $this->getMoney($agent_id,'left');	
				if((float)$left<(float)$money){
					$err =  array('err'=>array('1005'=>$this->errDefine('1005')));
					return $err;
				}
			}
		}
		

		$l_id = $this->db->insert($this->base->table('agent_finance'),array('admin_id'=>$_COOKIE['admin']['id'],'agent_id'=>$agent_id,'l_mount'=>$money,'l_type'=>$type,'l_date'=>$l_date,'l_desc'=>$desc));


		//更新总表
		if(in_array($type,$this->typePlus())){
				$c_mount = $money;
				$data['f_left'] = $ex['f_left'] + $c_mount;
				$data['f_rec'] = $ex['f_rec'] + $money;
					
		}elseif(in_array($type,$this->typeReduce())){
				$c_mount = -1*$money;
				$data['f_left'] = $ex['f_left'] + $c_mount;
				$data['f_pay'] = $ex['f_pay'] + $money;
		}	 
		 
		$this->db->update($this->base->table('agent'),$data,array('agent_id'=>$agent_id));
		
		return $l_id;
	}


	/**
	 * 对账
	 * @param  [type] $agent_id [用户ID]
	 * @return [type]       [description]
	 * @example        [D('WechatUserMoneyLog')->checkLog(D('User')->getID());]
	 */
	function checkLog($agent_id){
		$err_code = $this->errDefine();
		$err= array();
		 
		
		//日志账收入总额
		$where  = "  agent_id=".$agent_id; 
		$l_type_str = implode(',', $this->typePlus());
		$where .= ' and l_type in ('.$l_type_str.')';

		$rec = (int)$this->db->query("select sum(l_mount) from {$this->base->table('agent_finance')} where {$where} ",'One');

		//日志账支付总额	 
		$where  = "  agent_id=".$agent_id; 
		$l_type_str = implode(',', $this->typeReduce());
		$where .= ' and l_type in ('.$l_type_str.')';
		$pay = (int)$this->db->query("select sum(l_mount) from {$this->base->table('agent_finance')} where {$where} ",'One');

		if($rec<$pay){
			$err['1004'] = $err_code['1004'];
		}
		//与总帐表比较总支出
		$r = $this->getMoney($agent_id);
 
		if((float)$r['f_pay']!=(float)$pay){
			 $err['1002'] = $err_code['1002'];
		}
		//与总帐表比较总收入
		if((float)$r['f_rec']!=(float)$rec){
			 $err['1003'] = $err_code['1003'];
		}
		//总账表余额比较
		if(floatval($r['f_rec']-$r['f_pay'])!=(float)$r['f_left']){
			$err['1001'] = $err_code['1001'];
		}		
		 
		return $err;
	}

	/**
	 * 流水账
	 * @param  [type] $agent_id   [用户ID]
	 * @param  [type] $date_s [开始日期]
	 * @param  [type] $date_e [结束日期]
	 * @param  [type] $l_type [类型，1收入，2支出，具体参考typeDefine函数定义]
	 * @example [$ls = D('WechatUserMoneyLog')->flowLog(D('User')->getID());]
	 * @return [type]         [description]
	 */
		
	function flowLog($agent_id,$date_s=null,$date_e=null,$l_type=null){		 
		$w = ' where  agent_id='.$agent_id;
		if($date_s && $date_e){
			$w .= " and (DATE_FORMAT(l_date,'%Y-%m-%d') between '".$date_s."'  and '".$date_e."')";
		}elseif($date_s && !$date_e){
			$w .= " and (DATE_FORMAT(l_date,'%Y-%m-%d') >='".$date_s."' )";
		}elseif(!$date_s && $date_e){
			$w .= " and (DATE_FORMAT(l_date,'%Y-%m-%d') <='".$date_s."' )";
		}	

		if($l_type){			
			$l_type_str = implode(',',$l_type);
			$w .= ' and l_type in ({$l_type_str})'; 		
		}			 
		$types = $this->typeDefine();		
		$ls = $this->db->query("select l_id,l_type,l_mount,l_date,agent_id,l_desc from {$this->base->table('agent_finance')} {$w} order by l_id asc");
		$l_total = 0;
		foreach($ls as &$v){
			if(in_array($v['l_type'],$this->typePlus())){
					$m = 1;
					$v['plus'] = $v['l_mount'];
					$v['moneychange'] = $v['l_mount'];
			}
			if(in_array($v['l_type'],$this->typeReduce())){
					$m = -1;
					$v['reduce'] = $v['l_mount'];
					$v['moneychange'] = -1*$v['l_mount'];
			}
			$v['type_name'] = $types[$v['l_type']][1];
			
			$l_total += $m*$v['l_mount'];
			$v['l_sub'] =   $l_total;
		}
		return $ls;
	}



	/**
	 * 用户款项
	 * @param  [type] $uid  [用户ID]
	 * @param  [type] $type [款项类型，left表示余额,pay表示支出，rec表示充值]
	 * @return [array or number]       [description]
	 * @call  [D('WechatUserFinance')->getMoney(null,'left')];
	 */
	 function  getMoney($agent_id,$type=null){
	
		$rs = $this->db->query("select * from {$this->base->table('agent')} where agent_id={$agent_id}",'Row');	
		if(!$rs){
			$rs  = array('f_left'=>0,'f_pay'=>0,'f_rec'=>0);
		}
		switch ($type) {
			case 'left':
				$r  = $rs['f_left'];
				break;		
			case 'pay':
				$r  = $rs['f_pay'];
				break;	
			case 'rec':
				$r  = $rs['f_rec'];
				break;			
			default:
				$r = $rs;	
				break;		
		}
		return $r;
	}

	/**
	 * 统计
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	function  getStat($agent_id,$type){		 
		return $this->db->query("select sum(l_mount) from {$this->base->table('agent_finance')} where l_type in({$type_str}) and agent_id=".$agent_id,'One');
	}
	

	


}
?>